package com.xxpt.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SmsSender {
    public static String SIGN = "【信息平台】";
    private static final String key = "6d8d3a6c49e49228df407091a0862d35";
    private static final String HOST = "sms-api.luosimao.com";

    private static final String API_ENDPOINT = "http://" + HOST + "/v1";

//    static {
//        Properties properties = new Properties();
//        try {
//            properties.load(new InputStreamReader(SmsSender.class.getClassLoader().getResourceAsStream("sms.properties"), "UTF-8"));
//            SIGN = "【" + properties.getProperty("sms.sign") + "】";
//        } catch (Exception e) {
//            LOG.error("初始化短信配置失败:{}", e);
//        }
//    }

    public static void main(String[] args) {
        send("13661310804","短信发送测试");
    }

    private SmsSender() {
    }

    public static void send(String mobile, String message) {
        if (!message.endsWith(SIGN)) message += SIGN;
        CloseableHttpClient hc = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(API_ENDPOINT + "/send.json");

        String auth = "api:key-" + key;
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes());
        String authHeader = "Basic " + new String(encodedAuth);
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("mobile", mobile));
            params.add(new BasicNameValuePair("message", message));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

                @Override
                public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        return entity != null ? EntityUtils.toString(entity) : null;
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };

            String responseBody = hc.execute(httpPost, responseHandler);
            log.info(responseBody);
//            Map<String, Object> jsonRet = JsonUtils.decodeJson(responseBody, new TypeReference<Map<String, Object>>() {});
//            if (((Integer) jsonRet.get("error")).intValue() == 0) {
//                return true;
//            } else {
//                LOG.error("短信发送失败:{}", jsonRet.get("msg"));
//                return false;
//            }
        } catch (Exception e) {
            log.error("短信发送失败:{}", e);
        } finally {
            try {
                hc.close();
            } catch (Exception e) {
            }
        }
    }

}